package com.bp.hearthealth.pulse.lnapps.bp_network;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

/**
 * @author: isnoam
 * @package_name: BaseJsonDataEmptyStringAdapterFactory.java
 * @description：Gson解析非String类型字段，数据为空字符串“”，导致解析报异常的解决方案
 */
public class BpBaseJsonDataEmptyStringAdapterFactory implements TypeAdapterFactory {

    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {

        Class<? super T> rawType = typeToken.getRawType();
        TypeAdapter<T> originAdapter = gson.getAdapter(typeToken);

        //如果是String类型，则直接用原来的Adapter转换
        return String.class.equals(rawType) ? originAdapter : new Adapter(gson,originAdapter, rawType);
    }

    private class Adapter<E> extends TypeAdapter<E> {

        private final Gson context;
        private final Class<E> componentType;
        private final TypeAdapter<E> componentTypeAdapter;

        public Adapter(Gson context, TypeAdapter<E> componentTypeAdapter, Class<E> componentType) {
            this.context = context;
            this.componentTypeAdapter =componentTypeAdapter;
            this.componentType = componentType;
        }

        @Override
        public void write(JsonWriter out, E value) throws IOException {
            if(componentTypeAdapter != null) {
                componentTypeAdapter.write(out, value);
            }
        }

        @Override
        public E read(final JsonReader in) throws IOException {
            //如果下一个为JsonToken.STRING的起点，说明是下个节点是字符串
            if (in.peek() == JsonToken.STRING) {
                in.skipValue();
                return null;
            }
            if(componentTypeAdapter != null) {
                return componentTypeAdapter.read(in);
            }
            return null;
        }
    }
}